import json
import os
import re

from django import http
from django.contrib.auth import login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db import DatabaseError
from django.urls import reverse

from apps.item.models import Label
from apps.user.models import User
from django.shortcuts import render, redirect

from django.views import View
from django_redis import get_redis_connection


class LoginView(View):
    def get(self, request):
        """
        主页
        :param request:
        :return:
        """
        return render(request, 'login.html')

    def post(self, request):
        data = json.loads(request.body.decode("utf-8"))
        mobile = data.get("phone")

        password = data.get("password")

        if not all([password, mobile]):
            return http.JsonResponse({'code': "7410", 'errmsg': '数据异常，登录失败'})
        if re.search(r'^\d{11}$', mobile):
            # 手机号登录
            user = User.objects.filter(mobile=mobile)
            if not user:
                return http.JsonResponse({'code': "200", 'errmsg': '手机号不存在'})
        else:
            # 邮箱登录
            user = User.objects.filter(email=mobile)
            if not user:
                return http.JsonResponse({'code': "200", 'errmsg': '邮箱不存在'})
        print(user[0].password)
        if not user[0].check_password(password):
            return http.JsonResponse({'code': "200", 'errmsg': '账号或者密码错误'})
        login(request, user[0])
        return http.JsonResponse({'code': "0", 'errmsg': '登录成功'})


class RegisterView(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):

        data = json.loads(request.body.decode("utf-8"))
        print(data)
        mobile = data.get("phone")
        password = data.get("password")
        password2 = data.get("password2")
        username = data.get("name")
        if not all([username, password, password2, mobile]):
            print("*" * 30)
            return http.HttpResponseBadRequest('缺少必传参数')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseBadRequest('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseBadRequest('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('请输入正确的手机号码')

        # 保存注册数据
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
            label = Label.objects.create(name="未分类", user=user)
        except DatabaseError:
            return render(request, 'register.html', {'errmsg': '注册失败'})
        login(request, user)

        return http.JsonResponse({'code': "0", 'errmsg': '注册成功'})


class LogoutView(LoginRequiredMixin, View):
    """退出登录"""

    def get(self, request):
        """实现了退出了功能"""
        # 清除session
        logout(request)
        # 退出登录，重新定向到主页
        response = redirect(reverse('user:login'))
        response.delete_cookie("username")
        return response
